/*
 * @Author: your name
 * @Date: 2021-01-28 10:24:56
 * @LastEditTime: 2021-04-18 12:17:34
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \tower_defense\assets\scripts\game_scene\tower\arrow_tower.ts
 */

import { CannonTowerParams } from "../../game_data/tower_data/cannon_tower_params";
import { UG } from "../../modules/ugame";
import { FrameAnim } from "../../common/frame_anim";
import { CannonBullet } from "../bullet/cannon_bullet";

const { ccclass, property } = cc._decorator;

// 自定义类
@ccclass("cannon_tower_skin")
class cannon_tower_skin {
    @property(cc.SpriteFrame)   // 塔资源
    public tower_anim: Array<cc.SpriteFrame> = [];
    @property(cc.SpriteFrame)   // 子弹资源
    public bullet_anim: Array<cc.SpriteFrame> = [];
}

@ccclass
export class CannonTower extends cc.Component {

    @property(cc.Integer)  // 塔等级
    public tower_level: number = 1;
    @property(cc.Integer)
    public shoot_anim_sample: number = 10;    // 动画帧速率
    @property(cc.Node)
    public anim_node: cc.Node = null;
    @property(cc.Node)
    public bullet_icon_node: cc.Node = null;
    @property(cc.Graphics)  // 画笔
    public graphics: cc.Graphics = null;

    @property({             // 塔每个等级的皮肤
        type: cannon_tower_skin,
    })
    public level_tower_skin = [];

    @property(cc.Prefab)    // 子弹预制体
    public cannon_bullet_pre: cc.Prefab = null;

    public cannon_tower_frame_anim: FrameAnim = null;    // 保存自定义动画组件

    public bullet_root_node: cc.Node = null;    // 子弹存放节点
    public is_debug: boolean = true;           // 是否开启塔攻击范围绘制
    public tower_center_pos: cc.Vec2 = cc.v2();     // 塔中心坐标
    public tower_center_pos_in_tower_panel: cc.Vec2 = null; // tower_panel坐标系下的塔中心节点

    start() {
        this.scheduleOnce(this.cannon_tower_ai.bind(this), 0.1);
    }

    onLoad() {
        // this.is_debug = true;

        this.bullet_root_node = cc.find('Canvas/tower_panel/bullet_root');

        // 获取塔中心坐标
        this.tower_center_pos = this.get_tower_center_pos();
        // 
        this.bullet_icon_node.scale = 0;
        // this._set_tower_skin_by_level();

        // 开启debug
        // this._draw_tower_debug();

        // 绑定自定义动画组件
        this.cannon_tower_frame_anim = this.anim_node.addComponent(FrameAnim);
        this.cannon_tower_frame_anim.sprite_com = this.anim_node.getComponent(cc.Sprite);
        this.cannon_tower_frame_anim.anim_com = this.anim_node.getComponent(cc.Animation);
    }

    // 获取塔等级
    public get_tower_level(): any {
        if (this.tower_level >= 4) {
            // 防御塔已经是最高级
            return true;
        } else {
            return this.tower_level;
        }
    }

    // 根据等级设置塔图片
    private _set_tower_skin_by_level(): void {
        let sprite: cc.Sprite = this.anim_node.getComponent(cc.Sprite);
        sprite.spriteFrame = this.level_tower_skin[this.tower_level - 1].tower_anim[0];
    }

    // 升级塔
    public upgrade_tower(): any {
        // 塔有4个等级
        if (this.tower_level >= 4) {
            cc.log("已经最高级");
            return true;
        }

        // 开启debug
        this._draw_tower_debug();

        this.tower_level++;
        // 根据等级设置弓箭塔精灵
        this._set_tower_skin_by_level();

        return this.tower_level;
    }

    // 获取塔中心位置
    public get_tower_center_pos(): cc.Vec2 {
        let center_pos: cc.Vec2 = this.node.getPosition();

        let _a: cc.Vec2 = this.node.parent.convertToWorldSpaceAR(this.tower_center_pos);   // 转为世界坐标
        let _b: cc.Vec2 = this.node.parent.parent.convertToNodeSpaceAR(_a);

        this.tower_center_pos_in_tower_panel = _b;

        // this.graphics.circle(_b.x, _b.y, 5);
        // this.graphics.fill();

        return center_pos;
    }

    // 绘制塔攻击范围
    private _draw_tower_debug(): void {
        if (!this.is_debug) {
            return;
        }
        // 先清除
        this.graphics.clear();
        // 搜索半径
        let search_r: number = CannonTowerParams[this.tower_level - 1].search_R;
        // 绘制
        const _b: cc.Vec2 = this.tower_center_pos_in_tower_panel;
        this.graphics.circle(_b.x, _b.y, search_r);
        this.graphics.stroke();
    }

    // ===================================== 塔行为 ========================================
    // 填弹
    private _reload_cannon_bullet(): void {
        // 第四级炮塔不需要装填炸弹
        if (this.tower_level === 4) {
            return;
        }

        const start_pos_arr: Array<cc.Vec2> = [cc.v2(-24, 2), cc.v2(-24, 3), cc.v2(-24, 2), cc.v2(-24, 2)]; // 填弹开始位置
        const end_pos_arr: Array<cc.Vec2> = [cc.v2(3, 20), cc.v2(3, 21), cc.v2(3, 24), cc.v2(3, 24)];   // 填弹终点位置
        const delay_time_arr: Array<number> = [0.8, 1.5, 1.2];  // 填弹动画间隔
        
        // 设置对应等级的子弹图
        this.bullet_icon_node.getComponent(cc.Sprite).spriteFrame = this.level_tower_skin[this.tower_level - 1].bullet_anim[0];

        let t = cc.tween;
        t(this.bullet_icon_node)
            .delay(delay_time_arr[this.tower_level - 1])
            .call(() => {
                this.bullet_icon_node.scale = 1;
                this.bullet_icon_node.x = start_pos_arr[this.tower_level - 1].x;
                this.bullet_icon_node.y = start_pos_arr[this.tower_level - 1].y;
                this.bullet_icon_node.angle = -45;
            })
            .parallel(  // 并行执行 贝塞尔运动同时旋转角度
                t().by(0.4, { angle: -120 }),
                t().bezierTo(0.4, cc.v2(-10, 30), cc.v2(-10, 30), end_pos_arr[this.tower_level - 1])
            )
            .to(0.1, { scale: 0 })
            .start();
    }

    // 发射
    private _shoot_cannon_bullet_anim(level: number, enemy_world_pos: cc.Vec2, enemy: cc.Node): void {
        const start_pos_arr: Array<cc.Vec2> = [cc.v2(3, 16), cc.v2(3, 16), cc.v2(3, 16), cc.v2(-1, 20)];
        let start_world_pos: cc.Vec2 = this.anim_node.convertToWorldSpaceAR(start_pos_arr[this.tower_level - 1]);
        // 发射炮弹
        let cannon_bullet_node: cc.Node = cc.instantiate(this.cannon_bullet_pre);
        cannon_bullet_node.parent = this.bullet_root_node;
        let cannon_bullet_com: CannonBullet = cannon_bullet_node.getComponent(CannonBullet);
        cannon_bullet_com.bullet_level = level;
        cannon_bullet_com.shoot(level, start_world_pos, enemy_world_pos, enemy);
    }

    // 射击
    public shoot_anim(enemy_world_pos: cc.Vec2, enemy: cc.Node): void {
        this.cannon_tower_frame_anim.sprite_frame_arr = this.level_tower_skin[this.tower_level - 1].tower_anim;
        this.cannon_tower_frame_anim.sample = this.shoot_anim_sample;
        // 播放一次射击动画
        this.cannon_tower_frame_anim.play_once(() => {
            // cc.log('动画结束');
            // 播放完成,恢复塔图片
            this._set_tower_skin_by_level();
        });
        // 填弹
        this._reload_cannon_bullet();
        // 发射
        this._shoot_cannon_bullet_anim(this.tower_level, enemy_world_pos, enemy);
    }

    // 塔AI
    public cannon_tower_ai(): void {
        if (!this.tower_center_pos) {
            this.tower_center_pos = this.get_tower_center_pos();
        }
        // 获取塔中心位置
        let center_pos: cc.Vec2 = this.tower_center_pos;
        // 搜索半径
        let search_r = CannonTowerParams[this.tower_level - 1].search_R;
        // 扫描时间间隔
        let time: number = 0.1;
        // 攻击敌人
        let enemy: cc.Node = UG.search_enemy(center_pos, search_r);
        if (enemy) {
            // cc.log('找到敌人');
            let _enemy_world_pos: cc.Vec2 = enemy.parent.convertToWorldSpaceAR(cc.v2(enemy.x, enemy.y));   // 再敌人的父节点中，把敌人转为世界坐标
            // 播放射击动画
            this.shoot_anim(_enemy_world_pos, enemy);
            if (this.tower_level === 4) {
                time = 3.5;
            } else {
                time = 2;
            }
        }
        this.scheduleOnce(this.cannon_tower_ai.bind(this), time);
    }
}
